<template>
  <ToolbarButton
    type="popover"
    icon="i-ri-table-line"
    title="插入表格"
    popover-placement="bottom-start"
    popover-trigger="click"
    :popover-width="280"
    :large-icon="largeIcon"
    :hide-text="hideText"
    @popover-hide="handlePopoverHide"
  >
    <template #popover>
      <div class="table-inserter-panel">
        <div class="panel-header">
          <span class="header-title">插入表格</span>
          <span v-if="selectedRows > 0 && selectedCols > 0" class="header-size">
            {{ selectedRows }} × {{ selectedCols }}
          </span>
        </div>
        <div
          class="table-grid"
          @mousemove="handleMouseMove"
          @mouseleave="handleMouseLeave"
          @click="handleGridClick"
        >
          <div v-for="row in 8" :key="`row-${row}`" class="table-grid-row">
            <div
              v-for="col in 10"
              :key="`cell-${row}-${col}`"
              class="table-grid-cell"
              :class="{
                'is-selected': isCellSelected(row, col),
              }"
              :data-row="row"
              :data-col="col"
            ></div>
          </div>
        </div>
        <div class="panel-options">
          <label class="header-checkbox">
            <input
              v-model="withHeaderRow"
              type="checkbox"
              class="checkbox-input"
            />
            <span class="checkbox-label">包含表头</span>
          </label>
        </div>
        <div class="panel-footer" @click="handleCustomTableClick">
          自定义表格
        </div>
      </div>
    </template>
  </ToolbarButton>

  <!-- 自定义表格对话框 -->
  <Dialog
    v-model="showCustomDialog"
    title="插入表格"
    width="320px"
    @close="handleCancel"
  >
    <el-form :model="{ customRows, customCols }">
      <el-form-item label="行数:">
        <el-input
          v-model.number="customRows"
          type="number"
          :min="1"
          :max="100"
          placeholder="请输入行数"
          @keyup.enter="handleConfirm"
        />
      </el-form-item>
      <el-form-item label="列数:">
        <el-input
          v-model.number="customCols"
          type="number"
          :min="1"
          :max="100"
          placeholder="请输入列数"
          @keyup.enter="handleConfirm"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button
        type="primary"
        :disabled="!isValidInput"
        @click="handleConfirm"
      >
        确定
      </el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, computed, inject, type Ref } from "vue";
import type { Editor } from "@tiptap/vue-3";
import ToolbarButton from "../../../button/index.vue";
import { Dialog } from "../../../dialog";
import { closeAllToolbarPopups } from "../../../button/src/utils/toolbarPopupManager";

defineOptions({
  name: "InsertTable",
});

const props = withDefaults(
  defineProps<{
    largeIcon?: boolean;
    hideText?: boolean;
  }>(),
  {
    largeIcon: false,
    hideText: true,
  }
);

const { largeIcon, hideText } = props;

// 注入编辑器实例
const editor = inject<Ref<Editor>>("editor");

// 是否包含表头
const withHeaderRow = ref(true);

// 自定义表格对话框状态
const showCustomDialog = ref(false);
const customRows = ref(3);
const customCols = ref(3);

// 验证输入是否有效
const isValidInput = computed(() => {
  return (
    customRows.value > 0 &&
    customRows.value <= 100 &&
    customCols.value > 0 &&
    customCols.value <= 100
  );
});

// 当前悬停的行和列（1-based）
const hoverRow = ref(0);
const hoverCol = ref(0);

// 计算选中的行数和列数
const selectedRows = computed(() => hoverRow.value || 0);
const selectedCols = computed(() => hoverCol.value || 0);

// 判断格子是否被选中
const isCellSelected = (row: number, col: number) => {
  return row <= hoverRow.value && col <= hoverCol.value;
};

// 处理鼠标移动
const handleMouseMove = (e: MouseEvent) => {
  const target = e.target as HTMLElement;
  if (target.classList.contains("table-grid-cell")) {
    const row = parseInt(target.dataset.row || "0");
    const col = parseInt(target.dataset.col || "0");
    hoverRow.value = row;
    hoverCol.value = col;
  }
};

// 处理鼠标离开网格
const handleMouseLeave = () => {
  // 不清空，保留最后的选择状态
};

// 处理点击网格
const handleGridClick = (e: MouseEvent) => {
  const target = e.target as HTMLElement;
  if (target.classList.contains("table-grid-cell")) {
    const row = parseInt(target.dataset.row || "0");
    const col = parseInt(target.dataset.col || "0");

    if (row > 0 && col > 0 && editor?.value) {
      // 插入表格
      editor.value
        .chain()
        .focus()
        .insertTable({
          rows: row,
          cols: col,
          withHeaderRow: withHeaderRow.value,
        })
        .run();

      // 重置选择状态
      hoverRow.value = 0;
      hoverCol.value = 0;

      // 关闭 popover
      closeAllToolbarPopups();
    }
  }
};

// 处理 popover 隐藏
const handlePopoverHide = () => {
  // 重置选择状态
  hoverRow.value = 0;
  hoverCol.value = 0;
  // 重置表头选项
  withHeaderRow.value = true;
};

// 处理自定义表格点击
const handleCustomTableClick = () => {
  showCustomDialog.value = true;
  // 重置输入值
  customRows.value = 3;
  customCols.value = 3;
};

// 处理确认插入表格
const handleConfirm = () => {
  if (!isValidInput.value || !editor?.value) return;

  editor.value
    .chain()
    .focus()
    .insertTable({
      rows: customRows.value,
      cols: customCols.value,
      withHeaderRow: false,
    })
    .run();

  // 关闭对话框
  showCustomDialog.value = false;
  // 关闭 popover
  closeAllToolbarPopups();
  // 重置选择状态
  hoverRow.value = 0;
  hoverCol.value = 0;
};

// 处理取消
const handleCancel = () => {
  showCustomDialog.value = false;
  customRows.value = 3;
  customCols.value = 3;
};
</script>

<style scoped lang="scss">
.table-inserter-panel {
  padding: 12px;
  box-sizing: border-box;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: var(--editor-font-size-small, 12px);
  font-weight: 500;
  color: var(--editor-text-color);
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid
    var(--editor-border-color-light, var(--editor-border-color));
}

.header-title {
  flex: 1;
}

.header-size {
  color: var(--editor-primary-color);
  font-weight: 500;
  margin-left: 8px;
}

.table-grid {
  display: flex;
  flex-direction: column;
  gap: 2px;
  margin-bottom: 12px;
}

.table-grid-row {
  display: flex;
  gap: 2px;
}

.table-grid-cell {
  width: 20px;
  height: 20px;
  border: 1px solid var(--editor-border-color-light, var(--editor-border-color));
  background-color: var(--editor-color-white);
  cursor: pointer;
  transition: all 0.1s ease;

  &:hover {
    background-color: var(--editor-button-hover-background, #f2f2f2);
  }

  &.is-selected {
    border-color: var(--editor-primary-color);
    background-color: rgba(52, 128, 249, 0.1);

    &:hover {
      background-color: rgba(52, 128, 249, 0.15);
    }
  }
}

.panel-options {
  margin-bottom: 12px;
  padding: 8px 0;
  border-top: 1px solid
    var(--editor-border-color-light, var(--editor-border-color));
  border-bottom: 1px solid
    var(--editor-border-color-light, var(--editor-border-color));
}

.header-checkbox {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  user-select: none;
  font-size: var(--editor-font-size-small, 12px);
  color: var(--editor-text-color);
  transition: color 0.2s ease;

  &:hover {
    color: var(--editor-text-color);
  }
}

.checkbox-input {
  width: 16px;
  height: 16px;
  cursor: pointer;
  accent-color: var(--editor-primary-color, #1890ff);
  margin: 0;
}

.checkbox-label {
  font-size: var(--editor-font-size-small, 12px);
  line-height: 1.5;
}

.panel-footer {
  font-size: var(--editor-font-size-small, 12px);
  color: var(--editor-text-color-secondary, var(--editor-text-color));
  text-align: center;
  padding: 8px 0;
  min-height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background-color 0.2s ease;

  &:hover {
    background-color: var(--editor-button-hover-background, #f2f2f2);
    color: var(--editor-text-color);
  }
}
</style>
